#!/usr/bin/env python
# encoding=utf-8
import smtplib
import sys
from email.mime.text import MIMEText

import requests
from scpy.logger import get_logger

logger = get_logger(__file__)

reload(sys)
sys.setdefaultencoding("utf-8")

MAIL_LIST = ['kai.yan@socialcredits.cn', 'xu.du@socialcredits.cn']
UA = 'Mozilla/5.0 (X11; Ubuntu; Linux x86; rv:37.0) Gecko/20100101 Firefox/37.0'
LOGIN_URL = 'https://cloud.socialcredits.cn/api/client/login'
INDEX_URL = 'https://cloud.socialcredits.cn/portal'
POST_DATA = {
    'authId': 'demo@socialcredits.cn', 'authType': 'EMAIL',
    'password': '1bbd886460827015e5d605ed44252251'
}


def send_mail(subject, content, mailto_list):
    me = "portal<yucuntest123@sina.com>"
    msg = MIMEText(content, _subtype='plain', _charset='gb2312')
    msg['Subject'] = subject
    msg['From'] = me
    msg['To'] = ";".join(mailto_list)
    try:
        server = smtplib.SMTP()
        server.connect("smtp.sina.com")
        server.login('yucuntest123', "yucuntest")
        server.sendmail(me, mailto_list, msg.as_string())
        server.close()
        return True
    except:
        return False


def check():
    try:
        request = requests.Session()
        request.headers['User-Agent'] = UA
        login_data = request.post(LOGIN_URL, json=POST_DATA).content
        index_data = request.get(INDEX_URL).content
        return '555981810cf23ccaa6756202' in login_data and 'SocialCredits' in index_data
    except:
        return False


if __name__ == '__main__':
    now = time.strftime('%Y-%m-%d %H:%M:%S')
    if check():
        logger.info('checked at [%s] :  一切正常' % now)
    else:
        r = send_mail(u'Portal 报错啦~~', u'如题~~~', MAIL_LIST)
        logger.info('checked at [%s] :  发现异常, send mail : %s' % (now, r))
